#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速API测试脚本
用于验证API服务基本功能
"""

import requests
import json
import time


def test_api():
    """测试API基本功能"""
    base_url = "http://localhost:8080"
    
    print("微信公众号文章爬虫 API 快速测试")
    print("=" * 50)
    
    # 1. 测试健康检查
    print("1. 测试健康检查...")
    try:
        response = requests.get(f"{base_url}/api/health", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"✓ 健康检查成功: {data['status']}")
        else:
            print(f"✗ 健康检查失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"✗ 健康检查异常: {e}")
        return False
    
    # 2. 测试API文档
    print("\n2. 测试API文档...")
    try:
        response = requests.get(base_url, timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"✓ API文档获取成功: {data['service']}")
        else:
            print(f"✗ API文档获取失败: {response.status_code}")
    except Exception as e:
        print(f"✗ API文档获取异常: {e}")
    
    # 3. 测试参数验证
    print("\n3. 测试参数验证...")
    try:
        # 测试缺少URL参数
        response = requests.post(f"{base_url}/api/crawl", json={}, timeout=5)
        if response.status_code == 400:
            print("✓ 参数验证正常")
        else:
            print(f"✗ 参数验证异常: {response.status_code}")
    except Exception as e:
        print(f"✗ 参数验证测试异常: {e}")
    
    # 4. 测试实际爬取（使用已知可用的链接）
    print("\n4. 测试实际爬取...")
    test_url = "https://mp.weixin.qq.com/s/S9kSrZ7uavUD21G4ljyhOA"
    
    try:
        response = requests.post(
            f"{base_url}/api/crawl",
            json={
                "url": test_url,
                "format": "text"
            },
            timeout=30
        )
        
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                article = data['data']
                print(f"✓ 文章爬取成功")
                print(f"  标题: {article['title']}")
                print(f"  作者: {article['author']}")
                print(f"  内容长度: {article['content_length']} 字符")
                print(f"  内容预览: {article['content'][:100]}...")
            else:
                print(f"✗ 文章爬取失败: {data.get('error')}")
        else:
            print(f"✗ 请求失败: {response.status_code}")
            print(f"  响应: {response.text}")
    
    except Exception as e:
        print(f"✗ 文章爬取异常: {e}")
    
    print("\n" + "=" * 50)
    print("API测试完成！")
    return True


if __name__ == "__main__":
    test_api()